package de.uni_mannheim.informatik.ai.dame_ai.util;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;



public class XmlCompiler{
	protected String xmlHeader="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+NEWLINE;
	private static final String NEWLINE=System.getProperty("line.separator");
	private HashSet<XmlElement> processedElements;
	private int id=0;
	

	/**
	 * Generates a textual XML document from a tree of XmlElemnt Objects.
	 * 
	 * If element has children, they will recursively be compiled and appear
	 * as child tags in the returned document. If element has text content,
	 * it will occur as text content.
	 * @param element The root element of the XmlElemnt tree, from which the
	 * 				document should be generated.
	 * @return XML document representation of the tree rooted in element.
	 */
	public String compile(XmlElement element){
		processedElements= new HashSet<XmlElement>();
		return compile2(element);
	}
	
	/**
	 * Compiles element. Do not use this directly. Use compile() instead!</br>
	 * (because it does some initialization of the global context, which
	 * cannot be done inside of this recursive method)
	 */
	private String compile2(XmlElement element){
		String xml="";
		if(element==null)
			return null;
		if(processedElements.contains(element)){
			return element.getStubRep();
		}
		else{
			processedElements.add(element);
		}
		if(element.hasChildren()){
			element.getTag().setId(id);
			id++;
			xml+=element.getTag().opener()+NEWLINE;
			Collection<XmlElement> children = element.getChildren();
			for(XmlElement child: children){
				xml+=compile2(child)+NEWLINE;
			}
			xml+=element.getTag().closer();
		}
		else{
			xml+=element.toString();
		}
		return xml;
	}
	
	
	
	
}